package biz;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mysql.jdbc.StringUtils;

import util.PageVO;
import dao.CityDao;
import dao.ProvinceDao;
import entity.City;
import entity.Province;

@Service
@Transactional
public class AreaBiz {
	@Autowired
	private ProvinceDao provinceDao;
	@Autowired
	private CityDao cityDao;

	public PageVO<Province> listProvincesByPage(String name, int pageNum,int pageSize) {
		DetachedCriteria dc = DetachedCriteria.forClass(Province.class);
		if (!StringUtils.isNullOrEmpty(name)) {
			dc.add(Restrictions.like("name", name, MatchMode.ANYWHERE));
		}
		return provinceDao.listByPage(dc, pageNum, pageSize);
	}
	
	public List<Province> listProvinces(){
		try {
			return provinceDao.listAll("name");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public boolean updateProvince(Province province){
		return provinceDao.update(province);
	}
	
	public boolean addProvince(Province province){
		return (Integer)provinceDao.add(province)>0;
	}

	public PageVO<City> listCitiesByPage(int provinceId,String cityName, int pageNum, int pageSize) {
		DetachedCriteria dc=DetachedCriteria.forClass(City.class);
		dc.add(Restrictions.eq("province.id", provinceId));
		if (!StringUtils.isNullOrEmpty(cityName)) {
			dc.add(Restrictions.like("name", cityName, MatchMode.ANYWHERE));
		}
		return cityDao.listByPage(dc, pageNum, pageSize);
	}
	
	public boolean updateCity(City city){
		return cityDao.update(city);
	}
	
	public int addCity(City city){
		try{
			return (int) cityDao.add(city);
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}
	}

	public boolean delCity(City city) {
		return cityDao.delete(city);
	}

	public boolean delProvince(int id) {
		Province province = provinceDao.getById(id);
		return provinceDao.delete(province);
	}

	public List<City> listCities(int provinceId) {
		if (provinceId>0) {
			return cityDao.listCities(provinceId);
		} else {
			return null;
		}
	}

}
